package com.ubi.core.framework.job;

import com.ubi.core.utils.TimeLength;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;

import javax.annotation.PreDestroy;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @author raymond
 */
public class Scheduler {

    private static final int CORE_POOL_SIZE = 10;

    private final ScheduledThreadPoolExecutor executor;

    private final ConcurrentTaskScheduler scheduler;

    public Scheduler() {
        executor = new ScheduledThreadPoolExecutor(CORE_POOL_SIZE);
        scheduler = new ConcurrentTaskScheduler(executor);
    }

    public TaskScheduler getScheduler() {
        return scheduler;
    }

    public void triggerRightNow(Job job) {
        this.triggerAt(job, new Date());
    }

    public void triggerAt(Job job, Date date) {
        scheduler.schedule(job, date);
    }

    public void triggerAtFixRate(Job job, TimeLength timeLength) {
        scheduler.scheduleAtFixedRate(job, timeLength.toMilliseconds());
    }

    @PreDestroy
    public void shutdown() {
        executor.shutdownNow();
    }
}
